#ifndef CTHREAD_H
#define CTHREAD_H

#if _WIN32 || _WIN64
    #ifndef _CRT_SECURE_NO_WARNINGS
    #define _CRT_SECURE_NO_WARNINGS
    #endif
    #include <WinSock2.h> 
    #include <windows.h>
    //#include <process.h>
    #define TD_SLEEP(_secs) Sleep((_secs))
    #define TD_HANDLE HANDLE
    #define TD_INVALID (HANDLE)0
    #define TD_DEF(_proc, _arg) unsigned __stdcall _proc(void *_arg)
    #define TD_PREPROCESS
    #define TD_CREATEWITHID(_handle, _loop, _param, threadId) _handle = (TD_HANDLE)_beginthreadex(NULL, 0, _loop, _param, 0, &threadId)
    #define TD_CREATE(_handle, _loop, _param) _handle = (TD_HANDLE)_beginthreadex(NULL, 0, _loop, _param, 0,NULL)
    #define TD_JOIN(_handle) WaitForSingleObject(_handle, INFINITE)
    #define TD_TERMINATE(_handle) TerminateThread(_handle, 0)
    #define TD_CLOSE(_handle) CloseHandle(_handle);_handle=NULL
    #define TD_MUTEX CRITICAL_SECTION
    #define TD_MUTEXINIT(_handle) InitializeCriticalSection(_handle)
    #define TD_MUTEXENTER(_handle) EnterCriticalSection(_handle)
    #define TD_MUTEXLEAVE(_handle) LeaveCriticalSection(_handle)
    #define TD_MUTEXFINI(_handle) DeleteCriticalSection(_handle)
#else
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <signal.h>
    #include <fcntl.h>
    #include <termios.h>
    #include <sys/time.h>
    #include <sys/ioctl.h>
    #include <errno.h>
    #include <pthread.h>
    #define TD_SLEEP(_secs) usleep(_secs*1000)
    #define TD_HANDLE pthread_t
    #define TD_INVALID -1
    #define TD_DEF(_proc, _arg) void *_proc(void *_arg)
    #define TD_PREPROCESS  do{pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);} while(0)
    #define TD_CREATE(_handle, _loop, _param) pthread_create(&_handle, NULL, _loop, _param)
    #define TD_JOIN(_handle) pthread_join(_handle, NULL)
    #define TD_TERMINATE(_handle) pthread_cancel(_handle)
    #define TD_CLOSE(_handle) _handle=NULL
    #define TD_MUTEX pthread_mutex_t
    #define TD_MUTEXINIT(_handle) pthread_mutex_init(_handle, NULL)
    #define TD_MUTEXENTER(_handle) pthread_mutex_lock(_handle)
    #define TD_MUTEXLEAVE(_handle) pthread_mutex_unlock(_handle)
    #define TD_MUTEXFINI(_handle) pthread_mutex_destroy(_handle)
#endif



#endif